package cn.iocoder.yudao.module.trade.delivery.api;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.net.URLEncodeUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import cn.iocoder.yudao.framework.common.exception.Assertions;
import cn.iocoder.yudao.framework.common.exception.KnownServiceException;
import cn.iocoder.yudao.framework.common.util.json.JsonUtils;
import cn.iocoder.yudao.module.api.trade.delivery.ExpressApi;
import cn.iocoder.yudao.module.api.trade.delivery.dto.ExpressTrackQueryReqDTO;
import cn.iocoder.yudao.module.api.trade.delivery.dto.ExpressTrackRespDTO;
import cn.iocoder.yudao.module.trade.delivery.api.internal.ExpressQueryConvert;
import cn.iocoder.yudao.module.trade.delivery.api.internal.KdNiaoExpressQueryReqDTO;
import cn.iocoder.yudao.module.trade.delivery.api.internal.KdNiaoExpressQueryRespDTO;
import cn.iocoder.yudao.module.trade.framework.ExpressApiProperties;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.Collections;
import java.util.List;

/**
 * 快递鸟客户端
 *
 * @author jason
 */
@Slf4j
@AllArgsConstructor
public class KdNiaoExpressApiImpl implements ExpressApi {

    private static final String REAL_TIME_QUERY_URL = "https://api.kdniao.com/Ebusiness/EbusinessOrderHandle.aspx";

    private final RestTemplate restTemplate;
    private final ExpressApiProperties.KdNiaoConfig config;

    /**
     * 查询快递轨迹【免费版】
     * 仅支持 3 家：申通快递、圆通速递、百世快递
     *
     * @see <a href="https://www.yuque.com/kdnjishuzhichi/dfcrg1/wugo6k">接口文档</a>
     *
     * @param dto 查询请求参数
     * @return 快递轨迹
     */
    @Override
    public List<ExpressTrackRespDTO> getExpressTrackList(ExpressTrackQueryReqDTO dto) {
        // 发起请求
        KdNiaoExpressQueryReqDTO requestDTO = ExpressQueryConvert.INSTANCE.convert(dto);
        requestDTO.setExpressCode(dto.getExpressCode().toUpperCase());
        if (ObjUtil.equal(requestDTO.getExpressCode(), "SF")
            && StrUtil.isBlank(dto.getCustomerName())
            && StrUtil.length(dto.getPhone()) >= 4) {
            requestDTO.setCustomerName(StrUtil.subSufByLength(dto.getPhone(), 4));
        }
        KdNiaoExpressQueryRespDTO respDTO = httpRequest(config.getRequestType(), requestDTO);
        Assertions.notNull(respDTO, "无响应结果");
        // 处理结果
        if (!respDTO.getSuccess()) {
            throw new KnownServiceException(respDTO.getReason());
        }
        if (CollUtil.isEmpty(respDTO.getTracks())) {
            return Collections.emptyList();
        }
        return ExpressQueryConvert.INSTANCE.convertList(respDTO.getTracks());
    }

    /**
     * 快递鸟 API 请求
     *
     * @param <Req>       每个请求的请求结构 Req DTO
     * @param requestType 对应的请求指令 (快递鸟的 RequestType)
     * @param req         对应请求的请求参数
     */
    private <Req> KdNiaoExpressQueryRespDTO httpRequest(String requestType, Req req) {
        // 请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        // 请求体
        String reqData = JsonUtils.toJsonString(req);
        String dataSign = generateDataSign(reqData, config.getApiKey());
        MultiValueMap<String, String> requestBody = new LinkedMultiValueMap<>();
        requestBody.add("RequestData", reqData);
        requestBody.add("DataType", "2");
        requestBody.add("EBusinessID", config.getBusinessId());
        requestBody.add("DataSign", dataSign);
        requestBody.add("RequestType", requestType);
        log.info("[httpRequest][RequestType({}) 的请求参数({})]", requestType, requestBody);
        // 发送请求
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(requestBody, headers);
        ResponseEntity<String> responseEntity = restTemplate.exchange(REAL_TIME_QUERY_URL, HttpMethod.POST, requestEntity, String.class);
        log.info("[httpRequest][RequestType({}) 的响应结果({})", requestType, responseEntity);
        // 处理响应
        if (!responseEntity.getStatusCode().is2xxSuccessful()) {
            throw new KnownServiceException("快递鸟查询接口异常，状态码：" + responseEntity.getStatusCode());
        }
        return JsonUtils.parseObject(responseEntity.getBody(), KdNiaoExpressQueryRespDTO.class);
    }

    /**
     * 快递鸟生成请求签名
     * 参见 <a href="https://www.yuque.com/kdnjishuzhichi/dfcrg1/zes04h">签名说明</a>
     *
     * @param reqData 请求实体
     * @param apiKey  api Key
     */
    private String generateDataSign(String reqData, String apiKey) {
        String plainText = String.format("%s%s", reqData, apiKey);
        return URLEncodeUtil.encode(Base64.encode(DigestUtil.md5Hex(plainText)));
    }

}
